package com.yiliao.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yiliao.service.ChannelService;
import com.yiliao.util.DateUtils;
import com.yiliao.util.Md5Util;
import com.yiliao.util.MessageUtil;
import com.yiliao.util.PoolThread;

@Service
public class ChannelServiceImpl extends ICommServiceImpl implements ChannelService {

	@Override
	public Map<String, Object> getChannelBulletinList(int page) {
		try {
			return new HashMap<String, Object>() {
				private static final long serialVersionUID = 1L;
				{
					Map<String, Object> total = returnMap("SELECT COUNT(t_id) AS total FROM t_cps_bulletin");
					put("total", total.get("total"));
					List<Map<String, Object>> returnList = returnList(
							"SELECT t_id,t_title,t_img,t_content,DATE_FORMAT(t_create_time,'%Y-%m-%d %T') AS t_create_time  FROM t_cps_bulletin limit ?,10",
							(page - 1) * 10);
					put("rows", returnList);
				}
			};

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public MessageUtil saveOrUpdateChannelBulletin(Integer t_id, String t_title, String t_img, String t_content) {
		try {

			if (null == t_id) {

				String inStr = "INSERT INTO t_cps_bulletin (t_title, t_img, t_content, t_create_time) VALUES (?, ?, ?, ?);";

				executeSql(inStr, t_title.trim(), t_img.trim(), t_content.trim(),
						DateUtils.format(new Date(), DateUtils.FullDatePattern));

			} else {
				String uStr = "UPDATE t_cps_bulletin SET t_title=?, t_img=?, t_content=?  WHERE t_id= ?";

				executeSql(uStr, t_title, t_img, t_content, t_id);

			}
			return new MessageUtil(1, "操作成功!");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public MessageUtil delChannelBulletin(int t_id) {
		try {

			String delStr = "DELETE FROM t_cps_bulletin WHERE t_id = ?";

			executeSql(delStr, t_id);

			return new MessageUtil(1, "操作成功!");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public Map<String, Object> getFlooringPageList(int page) {
		try {

			return new HashMap<String, Object>() {
				private static final long serialVersionUID = 1L;
				{
					// 统计数据
					Map<String, Object> returnMap = returnMap("SELECT COUNT(t_id) AS total FROM t_cps_dow");
					put("total", returnMap.get("total"));

					// 获取数据列表
					List<Map<String, Object>> returnList = returnList(
							"SELECT t_id,t_name,t_jump_url,DATE_FORMAT(t_create_time,'%Y-%m-%d %T') t_create_time FROM t_cps_dow  LIMIT ?,10",
							(page - 1) * 10);

					put("rows", returnList);
				}
			};
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public MessageUtil saveOrUpdateFlooringPage(Integer t_id, String t_name, String t_jump_url) {
		try {
			// 新增
			if (null == t_id) {

				String inStr = "INSERT INTO t_cps_dow (t_name, t_jump_url, t_create_time) VALUES (?, ?, ?);";

				executeSql(inStr, t_name, t_jump_url, DateUtils.format(new Date(), DateUtils.FullDatePattern));

			} else { // 修改

				String uStr = "UPDATE t_cps_dow SET t_name=?, t_jump_url=? WHERE t_id = ? ";

				executeSql(uStr, t_name, t_jump_url, t_id);
			}

			return new MessageUtil(1, "操作成功!");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public MessageUtil delFlooringPage(int t_id) {
		try {

			String delStr = "DELETE FROM t_cps_dow WHERE t_id = ? ";

			executeSql(delStr, t_id);

			return new MessageUtil(1, "操作成功!");

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public Map<String, Object> getChannelList(int page) {
		try {

			return new HashMap<String, Object>() {
				private static final long serialVersionUID = 1L;
				{
					Map<String, Object> returnMap = returnMap(
							"SELECT COUNT(t_id) AS total FROM t_cps_user WHERE t_parent_id = 0 ");
					put("total", returnMap.get("total"));

					List<Map<String, Object>> returnList = returnList(
							"SELECT u.t_id,u.t_uid,u.t_login_phone,c.t_real_name,c.t_channel_name,u.t_start_using,c.t_gold_commission,c.t_vip_commission,c.t_settlement_type,DATE_FORMAT(u.t_create_time,'%Y-%m-%d %T') AS t_create_time FROM t_cps_user u LEFT JOIN t_cps c ON c.t_cps_id = u.t_id WHERE t_parent_id = 0 LIMIT ?,10",
							(page - 1) * 10);

					put("rows", returnList);
				}
			};

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public MessageUtil startOrStopChannel(int t_id, int start_using) {
		try {

			String uSql = "UPDATE t_cps_user SET t_start_using = ? WHERE t_id = ?";

			executeSql(uSql, start_using, t_id);

			return new MessageUtil(1, "操作成功!");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public Map<String, Object> getChannelDetail(int t_id) {
		try {

			return returnMap("SELECT * FROM t_cps c left join t_cps_user u on c.t_cps_id=u.t_id  WHERE c.t_cps_id = ?", t_id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	@Transactional
	public MessageUtil updateChannel(int t_id, String t_real_name,String t_channel_name,  Double t_gold_commission, Double t_vip_commission,
			int t_settlement_type, String t_bank_number, String t_bank_of_deposit, String t_account_name,
			String login_name,String login_pass,
			String t_settlement_method,String t_settlement_percent,String t_remarks,int t_channel_price) {
		if(t_id==0) {
			// t_id==0  新增
			// 注册信息到用户表中
			List<Map<String,Object>> returnList = this.returnList("select t_id from t_cps_user where t_login_phone=? ",login_name );
			if(!returnList.isEmpty()) {
				return new MessageUtil(0, "账号已注册,请勿重复注册.");
			}
			
			
			int userId = this.getFinalDao().getIEntitySQLDAO().saveData("insert into t_user (t_role,t_onLine,t_disable,t_create_time,t_referee,t_open_id) values (?,?,?,now(),?,?) ", 2,1,0,0,UUID.randomUUID().toString());
//			this.executeSql("update t_user set t_idcard=t_id +10000 where t_id=?", userId);
			
			//新建余额表数据
			this.executeSql("insert into t_balance (t_user_id) values (?)", userId);
			//注册到渠道代理用户表
			int t_cps_id = this.getFinalDao().getIEntitySQLDAO().saveData("insert into t_cps_user "
					+ "(t_login_phone,t_password,t_uid,t_create_time) values "
					+ "(?,?,?,now()) ", login_name,Md5Util.encodeByMD5(login_pass),userId);
			//注册渠道
			this.getFinalDao().getIEntitySQLDAO().saveData("insert into t_cps "
					+ "(t_cps_id,t_real_name,t_channel_name,t_vip_commission,t_gold_commission,"
					+ "t_settlement_type,t_bank_number,t_bank_of_deposit,t_account_name,"
					+ "t_remarks,t_settlement_method,t_settlement_percent,t_channel_price,t_create_time ) values "
					+ "(?,?,?,?,"
					+ "?,?,?,?,?,"
					+ "?,?,?,?,now()) ", t_cps_id,t_real_name,t_channel_name,t_vip_commission,t_gold_commission,
					t_settlement_type,t_bank_number,t_bank_of_deposit,t_account_name,t_remarks,t_settlement_method,t_settlement_percent,t_channel_price);
			
			//注册成功
			try {
				//新增渠道包
				new PoolThread(userId,t_channel_name).start();
			} catch (Exception e) {
				logger.info("渠道包新增失败");
				// TODO: handle exception
				e.printStackTrace();
			}
			} else {	
			//修改
			String uSql = "UPDATE t_cps SET "
					+ "t_real_name=?,t_channel_name=?, t_vip_commission=?, t_gold_commission=?,"
					+ " t_settlement_type=?, t_bank_number=?, "
					+ "t_bank_of_deposit=?, t_account_name=? , t_settlement_method=? , t_settlement_percent=?,t_channel_price=?  "
					+ "WHERE t_cps_id=? ";
			executeSql(uSql, t_real_name.trim(),t_channel_name, t_vip_commission, t_gold_commission, t_settlement_type, t_bank_number,
					t_bank_of_deposit, t_account_name,t_settlement_method,t_settlement_percent,t_channel_price,t_id);
			
			String uuSql ="update t_cps_user set t_create_time=now() ";
			if(StringUtils.isNotBlank(login_pass)) {
				uuSql=uuSql+",t_password= '"+Md5Util.encodeByMD5(login_pass)+"' ";
			}
			if(StringUtils.isNotBlank(login_name)) {
				uuSql=uuSql+",t_login_phone= '"+login_name+"' ";
			}
			uuSql=uuSql+" where t_id=?";
			this.executeSql(uuSql,t_id);
		}
		return new MessageUtil(1, "操作成功!");
}

	@Override
	public Map<String, Object> getChannelDataList(int page,int t_settlement_method ,String beginTime,String endTime,int condition_id,String condition_name) {
		try {
			HashMap<String, Object> hashMap = new HashMap<String, Object>();
			String qStr = "SELECT count(1) total FROM t_cps_day_income cd "
					+ " left join t_cps c on c.t_cps_id=cd.t_cps_id "
					+ " WHERE cd.t_parent_id = 0 ";
			if(t_settlement_method>=0) {
				qStr=qStr+ " and c.t_settlement_method="+t_settlement_method;
			}
			if(StringUtils.isNotBlank(endTime)) {
				qStr=qStr+ " and cd.t_day<='"+endTime+"' ";
			}
			if(StringUtils.isNotBlank(beginTime)) {
				qStr=qStr+ " and cd.t_day>='"+beginTime+"' ";
			}
			if(StringUtils.isNotBlank(condition_name)) {
				qStr=qStr+ " and c.t_channel_name  like '%"+condition_name+"%' ";
			}
			if(condition_id>0) {
				qStr=qStr+ " and cd.t_uid='"+(condition_id-10000)+"' ";
			}
			Map<String, Object> returnMap = returnMap(
					"SELECT COUNT(t_id) AS total FROM t_cps_day_income WHERE t_parent_id = 0 ");

			hashMap.put("total", returnMap.get("total"));
			
			qStr="";
			qStr = "SELECT cd.t_id,cd.t_uid,c.t_real_name ,c.t_channel_name,c.t_channel_price,"
					+ "cd.t_install_amount,"
					+ "cd.t_vip_income,"
					+ "cd.t_user_iphone,"
					+ "cd.t_user_android,"
					+ "case  when c.t_settlement_method=1 and cd.t_settlement_percent>0 "
					+ "then  FLOOR(cd.t_user_iphone * cd.t_settlement_percent/100)    else 0 end  t_cpa_iphone ,"
					+ "case  when c.t_settlement_method=1 and cd.t_settlement_percent>0 "
					+ "then  FLOOR(cd.t_user_android * cd.t_settlement_percent/100)  else 0 end  t_cpa_android ,"
					
					+ "cd.t_gold_income,cd.t_vip_income_two,cd.t_gold_income_two,cd.t_settle_accounts,cd.t_is_release,"
					+ "cd.t_settlement_percent,c.t_settlement_method,"
					+ "DATE_FORMAT(cd.t_day,'%Y-%m-%d') AS t_day FROM t_cps_day_income cd "
					+ " left join t_cps c on c.t_cps_id=cd.t_cps_id "
					+ " WHERE cd.t_parent_id = 0 ";
			if(t_settlement_method>=0) {
				qStr=qStr+ " and c.t_settlement_method="+t_settlement_method;
			}
			if(StringUtils.isNotBlank(endTime)) {
				qStr=qStr+ " and cd.t_day<='"+endTime+"' ";
			}
			if(StringUtils.isNotBlank(beginTime)) {
				qStr=qStr+ " and cd.t_day>='"+beginTime+"' ";
			}
			
			if(StringUtils.isNotBlank(condition_name)) {
				qStr=qStr+ " and c.t_channel_name  like '%"+condition_name+"%' ";
			}
			if(condition_id>0) {
				qStr=qStr+ " and cd.t_uid='"+(condition_id-10000)+"' ";
			}
			qStr=qStr+ " order by cd.t_day desc ,cd.t_cps_id desc LIMIT ?,10;";

			List<Map<String, Object>> returnList = returnList(qStr, (page - 1) * 10);

			returnList.forEach(s -> {
				s.putAll(returnMap(
						"SELECT c.t_account_name,c.t_bank_number,c.t_settlement_type FROM t_cps c LEFT JOIN t_cps_user cu ON c.t_cps_id = cu.t_id WHERE t_uid = ? ",
						s.get("t_uid")));
			});
			hashMap.put("rows", returnList);
			
			return  hashMap;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public MessageUtil settleAccountChannelData(int t_id) {
		try {

			String uSql = "UPDATE t_cps_day_income SET t_settle_accounts = 1 WHERE t_id = ? ";

			executeSql(uSql, t_id);

			return new MessageUtil(1, "操作成功!");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public Map<String, Object> getTwoChannelList(int page,int t_settlement_method ,int condition_id,String condition_name) {
		HashMap<String,Object> hashMap = new HashMap<String, Object>();
		try {

					String qStr="SELECT COUNT(cu.t_id) total FROM t_cps_user cu left join t_cps c on cu.t_id=c.t_cps_id  WHERE t_parent_id > 0";
					
					if(t_settlement_method>=0) {
						qStr=qStr+ " and c.t_settlement_method="+t_settlement_method;
					}
					
					if(condition_id>0) {
						qStr=qStr+ " and cu.t_uid='"+condition_id+"' ";
					}
					
					if(StringUtils.isNotBlank(condition_name)) {
						qStr=qStr+ " and c.t_channel_name like '%"+condition_name+"%' ";
					}
					Map<String, Object> map = returnMap(
							qStr);
					hashMap.put("total", map.get("total"));

					
					
					qStr="SELECT cu.t_uid,c.t_real_name,c.t_channel_name,cu.t_parent_id FROM t_cps_user cu  "
							+ "LEFT JOIN t_cps c ON c.t_cps_id = cu.t_id WHERE cu.t_parent_id > 0 ";
					
					if(t_settlement_method>=0) {
						qStr=qStr+ " and c.t_settlement_method="+t_settlement_method;
					}
					
					if(condition_id>0) {
						qStr=qStr+ " and cu.t_uid='"+condition_id+"' ";
					}
					
					if(StringUtils.isNotBlank(condition_name)) {
						qStr=qStr+ " and c.t_channel_name like '%"+condition_name+"%' ";
					}
					
					qStr=qStr+ " order by cu.t_id desc  LIMIT ?,10";
					
					List<Map<String, Object>> returnList = returnList(
							qStr,
							(page - 1) * 10);

					returnList.forEach(s -> {
						// 获取父级的编号和名称
						s.putAll(returnMap(
								"SELECT cu.t_uid parentId,c.t_channel_name parent_anme FROM t_cps_user cu LEFT JOIN t_cps c ON c.t_cps_id = cu.t_id WHERE cu.t_id = ?",
								s.get("t_parent_id")));
						// 得到二级代理的所有的充值收益和vip收益
						s.putAll(returnMap(
								"SELECT SUM(t_gold_income) gold_income,SUM(t_vip_income) vip_income FROM t_cps_day_income WHERE t_uid = ?",
								s.get("t_uid")));

						// 得到已经结算了多少收益
						Map<String, Object> returnMap = returnMap(
								"SELECT SUM(t_gold_income) gold_income,SUM(t_vip_income) vip_income FROM t_cps_day_income WHERE t_uid = ? AND t_settle_accounts = 1",
								s.get("t_uid"));

						// 已结算的金额
						s.put("settlement",
								new BigDecimal(null == returnMap.get("gold_income") ? "0"
										: returnMap.get("gold_income").toString())
												.add(new BigDecimal(null == returnMap.get("vip_income") ? "0"
														: returnMap.get("vip_income").toString()))
												.setScale(2, BigDecimal.ROUND_DOWN));

					});
					hashMap.put("rows", returnList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return hashMap;
	}

	@Override
	public Map<String, Object> getChannelMaterial(int page) {
		try {

			return new HashMap<String, Object>() {
				private static final long serialVersionUID = 1L;
				{
					Map<String, Object> returnMap = returnMap("SELECT COUNT(t_id) AS total FROM t_cps_material");
					put("total", returnMap.get("total"));
					
					List<Map<String,Object>> returnList = returnList("SELECT t_id,t_img,t_size,DATE_FORMAT(t_create_time,'%Y-%m-%d %T') AS t_create_time FROM t_cps_material LIMIT ?,10", (page-1)*10);
					
					put("rows", returnList);
				}
			};

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public MessageUtil delChannelMaterial(int t_id) {
		try {
			
			executeSql("DELETE  FROM t_cps_material WHERE t_id = ?", t_id);
			
			return new MessageUtil(1, "删除成功!");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public MessageUtil saveOrUpdateChannelMaterial(Integer t_id, String t_img, String t_size) {
		try {
			
			if(null == t_id || t_id <= 0) {
				String inSql = "INSERT INTO t_cps_material (t_img, t_size, t_create_time) VALUES (?, ?, ?)";
				
				executeSql(inSql, t_img,t_size,DateUtils.format(new Date(), DateUtils.FullDatePattern));
			}else {
				String uSql = "UPDATE t_cps_material SET t_img=?, t_size=? WHERE t_id= ?";
				
				this.executeSql(uSql, t_img,t_size,t_id);
			}
			
			return new MessageUtil(1, "操作成功!");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public Map<String, Object> getChannelList(int page, int t_settlement_method, int condition_id,
			String condition_name) {
		HashMap<String,Object> hashMap = new HashMap<String, Object>();
		try {
				{
					Map<String, Object> returnMap = returnMap(
							"SELECT COUNT(t_id) AS total FROM t_cps_user WHERE t_parent_id = 0 ");
					hashMap.put("total", returnMap.get("total"));

					String qStr="SELECT c.t_settlement_method,c.t_settlement_percent,"
					+ "u.t_id,u.t_uid,u.t_login_phone,c.t_real_name,c.t_channel_name,c.t_channel_price,u.t_start_using,c.t_gold_commission,"
					+ "c.t_vip_commission,c.t_settlement_type,DATE_FORMAT(u.t_create_time,'%Y-%m-%d %T') AS t_create_time "
					+ "FROM t_cps_user u "
					+ "LEFT JOIN t_cps c ON c.t_cps_id = u.t_id "
					+ "WHERE t_parent_id = 0";
					
					if(t_settlement_method>=0) {
						qStr=qStr+ " and c.t_settlement_method="+t_settlement_method;
					}
					if(condition_id>0) {
						qStr=qStr+ " and u.t_uid='"+(condition_id-10000)+"' ";
					}
					if(StringUtils.isNotBlank(condition_name)) {
						qStr=qStr+ " and c.t_channel_name like '%"+condition_name+"%' ";
					}
					
					qStr=qStr+ " order by u.t_start_using ,u.t_id desc LIMIT ?,10";
					List<Map<String, Object>> returnList = returnList(
							qStr,
							(page - 1) * 10);

					hashMap.put("rows", returnList);
				}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return hashMap;
	}

	@Override
	public MessageUtil setChannelPercent(int t_id, int t_settlement_percent) {
		try {
			Map<String, Object> returnMap = this.returnMap("select t_day,t_uid from t_cps_day_income where t_id =? " ,t_id);
			executeSql("update t_cps_day_income set  t_settlement_percent=? WHERE t_id = ?",t_settlement_percent, t_id);
			//更新当天数据下的比例
			//1.346  t_cps_user  获取 27
			this.executeSql("update t_cps_day_income set  t_settlement_percent=? WHERE t_day = ? and t_parent_id=("
					+ "select t_id from t_cps_user where t_uid=?"
					+ ")", t_settlement_percent,returnMap.get("t_day"),returnMap.get("t_uid"));
			return new MessageUtil(1, "修改成功!");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public MessageUtil setChannelrelease(int t_id, int t_is_release) {
		try {
			Map<String, Object> returnMap = this.returnMap("select t_day,t_uid from t_cps_day_income where t_id =? " ,t_id);
			executeSql("update t_cps_day_income set  t_is_release=? WHERE t_id = ?",t_is_release, t_id);
			
			this.executeSql("update t_cps_day_income set  t_is_release=? WHERE t_day = ? and t_parent_id=("
					+ "select t_id from t_cps_user where t_uid=?"
					+ ")", t_is_release,returnMap.get("t_day"),returnMap.get("t_uid"));
			return new MessageUtil(1, "修改成功!");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	@Override
	public Map<String, Object> getChannelDowList(Integer page, String pageSize) {
		try {

			return new HashMap<String, Object>() {
				private static final long serialVersionUID = 1L;
				{
					Map<String, Object> returnMap = returnMap("SELECT COUNT(1) AS total FROM t_channel_pac");
					put("total", returnMap.get("total"));
					
					List<Map<String,Object>> returnList = returnList("SELECT t_id,t_pac_name,t_pac_version,DATE_FORMAT(t_create_time,'%Y-%m-%d %T') AS t_create_time FROM t_channel_pac LIMIT ?,10", (page-1)*10);
					
					put("rows", returnList);
				}
			};

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public MessageUtil delChannelPacById(Integer t_id) {
		try {
			
			String delStr = "DELETE FROM t_channel_pac WHERE t_id = ?";

			executeSql(delStr, t_id);
			
			return new MessageUtil(1, "操作成功!");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	@Override
	public MessageUtil addChannelPac(String t_pac_name, String t_pac_version) {
		try {
			try {
				
				int waitFor = Runtime.getRuntime().exec("rm -rf /speed/img/apk").waitFor();
				logger.info("linux语句执行结束:{}",waitFor);
			} catch (Exception e) {
				e.printStackTrace();
			}
			String addStr = "insert into  t_channel_pac (t_pac_name,t_pac_version,t_create_time) values (?,?,now())";
			
			executeSql(addStr, t_pac_name,t_pac_version);
			
			executeSql("DELETE FROM t_channel_pac_dow_log");
			
			return new MessageUtil(1, "操作成功!");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
